import * as React from "react";
import { Link, useLocation, useNavigate } from "react-router-dom";
import {
  UserOutlined,
  LockOutlined,
  SafetyCertificateOutlined,
  MobileOutlined,
  MailOutlined,
} from "@ant-design/icons";
import { message, Checkbox, Card } from "antd";
import { useAppDispatch, useAppSelector } from "apis/module/store";
import { loginHandler } from "apis/module/store/slices/userSlice";
import { LoginParamsType } from "apis/module/sys";
import {
  BizForm,
  BizFormItem,
  BizFormItemInput,
  BizFormItemCaptcha,
  BizFormItemPassword,
  IdentifyCode,
} from "biz-component/components/biz-form";
import { useAsync } from "rc-hooks";
import { sleep } from "ut2";
import { storageStore } from "utils";
import { useStyle } from "./useStyle";

async function sendCaptcha(mobile: string) {
  await sleep(2000);
  message.success(`验证码已发送至 ${mobile}`);
  return;
}

async function getGraphValidateCode() {
  await sleep();
  return ``;
}

// https://github.com/reach/router/issues/414
type LocationProps = {
  state: {
    from?: Location;
  };
};

const Login = () => {
  const styles = useStyle();
  const navigate = useNavigate();
  const location = useLocation() as unknown as LocationProps;
  const { isAuth, processing } = useAppSelector((state) => state.user);
  const dispatch = useAppDispatch();

  const [form] = BizForm.useForm();
  let from = React.useRef(location.state?.from ?? { pathname: "/app/index" });
  console.log("[ before in login, from ]", from);

  React.useEffect(() => {
    console.log("after login ...");
    if (isAuth) {
      console.log("after login , goto", from.current);
      navigate(from.current, { replace: true });
    }
  }, [isAuth]);

  // const {
  //   loading,
  //   data: src,
  //   refresh: refreshGraphValidateCode,
  // } = useAsync(getGraphValidateCode);

  const onSubmit = React.useCallback(async () => {
    const res = await form.validateFields();
    console.log("login submit res:", res);

    if (res) {
      const values: LoginParamsType = {
        username: res.userName,
        password: res.password,
      };
      if (values.username && values.password) {
        // 无实际意义，特殊处理下，mock 时用于 `/manager/medical-staff/staff-info-His` 判断用户
        if (process.env.REACT_APP_API_MOCKING === "true") {
          storageStore.setValue("account", res.userName);
        }

        dispatch(loginHandler(values));
      } else {
        // mobile
        console.error("登录参数好像不对了:", values, res);
      }
    }
  }, [form]);

  return (
    <Card
      title="用户登录"
      bordered={false}
      style={{ minWidth: 320, boxShadow: "none" }}
      headStyle={{ border: "0 none", fontSize: 24, paddingBottom: 30 }}
      bodyStyle={{ paddingTop: 0 }}
    >
      <BizForm
        name="form-login"
        form={form}
        onFinish={onSubmit}
        submitter={{
          noReset: true,
          submitText: "登录",
          submitButtonProps: {
            size: "large",
            block: true,
            loading: processing,
          },
        }}
        hideLabel
        // size="large"
      >
        <BizFormItemInput
          name="userName"
          placeholder="请输入用户名"
          inputProps={{
            prefix: <UserOutlined />,
          }}
          label="用户名"
          required
        />
        <BizFormItemPassword
          name="password"
          placeholder="请输入密码"
          inputProps={{
            prefix: <LockOutlined />,
          }}
          label="密码"
          required
          validated={false}
        />
        {/* <BizFormItemInput
          name="email"
          type="email"
          placeholder="请输入邮箱"
          inputProps={{
            prefix: <MailOutlined />,
          }}
          label="邮箱"
          required
        />
        <BizFormItemInput
          name="mobile"
          type="mobile"
          placeholder="请输入手机号码"
          inputProps={{
            prefix: <MobileOutlined />,
          }}
          label="手机号码"
          required
        /> */}

        {/* <BizFormItemCaptcha
          name="captcha"
          normalize={(val) => val.replace(/[^\d]/g, "")}
          placeholder="请输入验证码"
          maxLength={6}
          inputProps={{
            prefix: <SafetyCertificateOutlined />,
          }}
          required
          label="验证码"
          onGetCaptcha={async () => {
            try {
              // 验证手机号码或邮箱是否正确
              await form.validateFields(["mobile"]);
            } catch (err) {
              message.error("请输入正确的手机号码");
              return false;
            }

            // 发送验证码
            return sendCaptcha(form.getFieldValue("mobile"));
          }}
        />
        <BizFormItemInput
          name="verifyCode"
          placeholder="请输入图片验证码"
          inputProps={{
            prefix: <SafetyCertificateOutlined />,
          }}
          contentAfter={
            <IdentifyCode
              loading={loading}
              src={src}
              onClick={refreshGraphValidateCode}
            />
          }
          label="图片验证码"
          required
        /> */}
        <BizFormItem>
          <BizFormItem noStyle name="autoLogin" valuePropName="checked">
            <Checkbox>自动登录</Checkbox>
          </BizFormItem>
          <a style={{ float: "right" }}>忘记密码</a>
        </BizFormItem>
      </BizForm>
    </Card>
  );
};

export default Login;
